﻿using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using ManagerClient.AuthentificationService;

namespace ManagerClient.Manage.Views
{
    /// <summary>
    ///     Interaction logic for ManageMenuControl.xaml
    /// </summary>
    public partial class ManageMenuControl : UserControl
    {
        private ListBox dragSource;

        public ManageMenuControl()
        {
            InitializeComponent();
        }

        private static object GetDataFromListBox(ListBox source, Point point)
        {
            var element = source.InputHitTest(point) as
                          UIElement;

            if (element != null)
            {
                object data = DependencyProperty.UnsetValue;

                while (data == DependencyProperty.UnsetValue)
                {
                    data = source.ItemContainerGenerator.ItemFromContainer(element);

                    if (data == DependencyProperty.UnsetValue)
                    {
                        element = VisualTreeHelper.GetParent(element) as
                                  UIElement;
                    }

                    if (element == source)
                    {
                        return
                            null;
                    }
                }

                if (data != DependencyProperty.UnsetValue)
                {
                    return data;
                }
            }

            return
                null;
        }

        private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var parent = (ListBox) sender;

            dragSource = parent;

            object data = GetDataFromListBox(dragSource, e.GetPosition(parent));

            if (data != null)
            {
                DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
            }
        }

        private void ListBox_Drop(object sender, DragEventArgs e)
        {
            var parent = (ListBox) sender;


            object data = e.Data.GetData(typeof (Dish));

            ((IList) dragSource.ItemsSource).Remove(data);

            parent.Items.Add(data);
        }
    }
}